package com.open.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.open.bean.IpWhite;
import com.open.bean.vo.OpenVo;
import com.open.component.JwtComponent;
import com.open.result.OpenResult;
import com.open.service.RequestRecordService;
import com.open.service.impl.IpWhiteServiceImpl;
import com.open.service.impl.RequestRecordServiceImpl;
import com.open.util.InterceptorBeanUtil;
import com.open.util.OpenRequestUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author tanyongpeng
 * <p>des</p>
 **/
public class OpenAIConfig implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        boolean state;
        Map<String,Object> infoMap = new HashMap<>();
        if (requestURI.contains("/request/open/send/sse")) {
            response.setHeader("Cache-Control", "no-store,no-cache, must-revalidate");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Expires", "-1");
            return true;
        }else {
            state = handle(request, response, infoMap);
            if (state){
                return true;
            }else {
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                PrintWriter out = response.getWriter();
                out.write(JSONUtil.parse(infoMap).toString());
                out.flush();
                out.close();
                return false;
            }
        }
    }

    public boolean handle(HttpServletRequest request,HttpServletResponse response,Map<String,Object> infoMap){
        response.setHeader("Cache-Control", "no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "-1");
        String token = request.getHeader("token");
        try{
            //token验证
            JwtComponent jwtComponent = InterceptorBeanUtil.getBean(JwtComponent.class, request);
            DecodedJWT tokenInfo = jwtComponent.getTokenInfo(token);
            String wId = jwtComponent.getUserWId(request);
            OpenVo openVo = OpenRequestUtil.vefUser(request);
            if (!openVo.isState()) {
                infoMap.put("code", OpenResult.WEB_ERROR);
                infoMap.put("msg",openVo.getMsg());
                return false;
            }else {
                if (StrUtil.isNotBlank(wId)){
                    IpWhiteServiceImpl ipWhiteService = InterceptorBeanUtil.getBean(IpWhiteServiceImpl.class, request);
                    IpWhite ipWhite = ipWhiteService.lambdaQuery().eq(IpWhite::getWid, wId).one();
                    if (ipWhite.getIpStatus() == 1){
                        infoMap.put("code", OpenResult.WEB_ERROR);
                        infoMap.put("msg","当前账号被封禁");
                    }else if(ipWhite.getIpStatus() == 3){
                        infoMap.put("code", OpenResult.WEB_ERROR);
                        infoMap.put("msg","当前账号正在审核，请稍等...");
                    }else {
                        return true;
                    }
                }else {
                    return true;
                }
            }
        }catch (Exception e){
            infoMap.put("code", OpenResult.WEB_ERROR);
            infoMap.put("msg","身份已过期，请重新登录本网站");
        }
        return false;
    }

}
